<template>
    <div class="goods-add-form">
        <!-- 盘点基本信息区块 -->
        <div class="section">
            <h2 class="section-title" style="display:flex"> {{ qty_code }}
                <div class="action-buttons" style="position: relative;left:850px; top:-10px;">
                    <el-button @click="handleEdit(mainForm.qty_audit_status)">
                        编辑
                    </el-button>
                    <el-button @click="handleDelete">
                        删除
                    </el-button>
                    <el-button @click="handleExamine(mainForm.qty_audit_status)">
                        审核
                    </el-button>
                </div>
            </h2>

            <table style="width: 100%; border-collapse: collapse;border: none;">
                <tbody>
                    <!-- 盘点类型 -->
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">盘点类型</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">
                            <span>{{ qty_type_label }}</span>
                        </td>

                        <!-- 仓库 -->
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">仓库</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">
                            <span>{{ mainForm.warehouse_name }}</span>
                        </td>

                        <!-- 盘点人 -->
                        <td style="padding: 10px 0px; color: #666;">盘点人</td>
                        <td style="padding: 10px 0px 10px 10px;">
                            <span>{{ mainForm.qty_clerk }}</span>
                        </td>
                    </tr>

                    <!-- 盘点日期 -->
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">盘点日期</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">
                            <span>{{ formatDate(mainForm.qty_startdate) }}</span>
                        </td>

                        <!-- 结束日期 -->
                        <td style="padding: 10px 0px 10px 10px; color: #666;">结束日期</td>
                        <td style="padding: 10px 0px 10px 10px;">
                            <span>{{ formatDate(mainForm.qty_end) }}</span>
                        </td>
                    </tr>

                    <!-- 创建信息行（不可编辑） -->
                    <tr>
                        <td style="padding: 10px 0px; color: #666;">创建人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ mainForm.create_by }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">创建时间</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ formatDate(mainForm.create_time) }}
                        </td>
                    </tr>

                    <!-- 审核信息行（不可编辑） -->
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">审核状态</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{
                            getStatusText(mainForm.qty_audit_status) }}</td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">审核人</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{
                            mainForm.qty_audit_by
                            }}</td>
                        <td style="padding: 10px 0px; color: #666;">审核时间</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ formatDate(mainForm.qty_audit_time) }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 盘点产品明细区块 -->
        <div class="section">
            <h2 class="section-title" style="display:flex">盘点产品明细</h2>

            <el-table :data="tableData" border style="width: 90%" :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" :cell-style="{ textAlign: 'center' }">
                <el-table-column prop="pro_name" label="货品名称" width="150" />
                <el-table-column prop="pro_code" label="货品编号" width="130" />
                <el-table-column prop="pro_brand" label="品牌" width="130" />
                <el-table-column prop="pro_model" label="规格型号" width="110" />
                <el-table-column label="单位" width="100">
                    <template #default="scope">
                        <span>{{ statusValue(scope.row.unitmeas_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="stock_numder" label="库存数量" width="130" />
                <el-table-column prop="inventory_numder" label="盘点数量" width="100" />
                <el-table-column prop="proddti_loss" label="盘亏数量" width="100" />
                <el-table-column prop="proddti_profit" label="盘盈数量" width="100" />
                <el-table-column label="盘亏金额" width="100">
                    <template #default="scope">
                        <span>{{ scope.row.proddti_loss_money.toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="盘盈金额" width="100">
                    <template #default="scope">
                        <span>{{ scope.row.proddti_profit_money.toFixed(2) }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div class="summary-row">
                <span>合计</span>
                <div class="summary-values">
                    <span>盘亏总量：{{ totalLossQuantity }}</span>
                    <span>盘盈总量：{{ totalProfitQuantity }}</span>
                    <span>盘亏总金额：{{ totalLossAmount.toFixed(2) }}</span>
                    <span>盘盈总金额：{{ totalProfitAmount.toFixed(2) }}</span>
                </div>
            </div>
        </div>

        <!--审核状态-->
        <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
            <template #header>
                <div style="text-align: left; font-size: 16px; font-weight: bold;">
                    审核
                </div>
            </template>
            <hr>
            <div style="text-align: left;padding: 10px 0px;">
                <p>审核结果</p>
                <div class="my-2 ml-4">
                    <el-radio-group v-model="auditStatus">
                        <el-radio value="1">通过</el-radio>
                        <el-radio value="2">驳回</el-radio>
                    </el-radio-group>
                </div>
                <div>
                    <p>审核意见</p>
                    <el-input v-model="auditOpinion" style="width: 350px;height: 90px;"
                        :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入" />
                </div>
            </div>
            <hr>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="close">取消</el-button>
                    <el-button type="primary" @click="updateAudit">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { useWarehouseStore } from '@/storejs/warehouseStore';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';

const router = useRouter();

// 表格数据
const tableData = ref([]);

// 控制审核状态的显示
const centerDialogVisible = ref(false)
const auditStatus = ref('1') // 审核状态
const auditOpinion = ref("") // 审核意见

// 主表数据
const mainForm = ref({
    qty_id: 0,
    qty_audit_status: '',
    qty_clerk: '',
    qty_startdate: '',
    create_by: "",
    create_time: '',
    qty_audit_by: "",
    qty_audit_time: "",
    warehouse_name: ""
});

// 单位字典
const dict_labelSwer = ref([]);
// 盘点类型字典
const qtyTypeOptions = ref([]);

// 页面跳转获取数据
const warehouseStore = useWarehouseStore()
const qty_code = ref(warehouseStore.qty_code || '')
const qty_type_label = ref('');

// 获取审核状态文本
const getStatusText = (status) => {
    switch (status) {
        case "0": return "待审核";
        case "1": return "已审核";
        case "2": return "驳回";
        default: return "未知状态";
    }
};

// 计算盘亏总量
const totalLossQuantity = computed(() => {
    return tableData.value.reduce((sum, item) => {
        return sum + (Number(item.proddti_loss) || 0);
    }, 0);
});

// 计算盘盈总量
const totalProfitQuantity = computed(() => {
    return tableData.value.reduce((sum, item) => {
        return sum + (Number(item.proddti_profit) || 0);
    }, 0);
});

// 计算盘亏总金额
const totalLossAmount = computed(() => {
    return tableData.value.reduce((sum, item) => {
        return sum + (Number(item.proddti_loss_money) || 0);
    }, 0);
});

// 计算盘盈总金额
const totalProfitAmount = computed(() => {
    return tableData.value.reduce((sum, item) => {
        return sum + (Number(item.proddti_profit_money) || 0);
    }, 0);
});

// 单位值转换
function statusValue(row) {
    if (!row) return "无";
    const unit = dict_labelSwer.value.find((d) => d.dict_value == row);
    return unit ? unit.dict_label : "无";
}

//修改库存审核状态盘点
function handleExamine(Status) {
    if (Status == "1") {
        ElMessage.info(`订单${qty_code.value}已审核,不可以再次审核`)
    } else {
        //显示 模态框
        centerDialogVisible.value = true;
    }
}

//点击修改状态关闭模态框  
function updateAudit() {
    if (auditStatus.value !== "1" && auditStatus.value !== "2") {
        ElMessage.error('请选择审核状态');
        return;
    }
    axios.put("http://localhost:5181/api/Inv_Qty/Inv_Qty_examineUpdate",
        {
            qty_code: qty_code.value,
            qty_audit_status: auditStatus.value,
            qty_audit_by: localStorage.getItem('userLName'),
            qty_audit_opinion: auditOpinion.value,
            qty_audit_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
        },
        {
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        }
    ).then((result) => {
        if (result.data > 0) {
            if (auditStatus.value == 1) {
                ElMessage.success('审核通过');
                close();
                handle();
            } else {
                ElMessage.error('审核驳回');
                handle();
            }
        } else {
            ElMessage.error('审核失败');
        }
    }).catch((err) => {
        console.info(err)
    });
}

//取消审核按钮
function close() {
    centerDialogVisible.value = false
    auditStatus.value = "1"
    auditOpinion.value = ""
}

//库存盘点判断是否可以删除
function handleDelete() {
    if (mainForm.value.qty_audit_status == "1") {
        ElMessage.info(`订单${qty_code.value}已审核,不可以进行删除`)
    } else {
        ElMessageBox.confirm(
            `你确定要删除单号为 ${qty_code.value} 的盘点记录吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => {
            axios.put("http://localhost:5181/api/Inv_Qty/Inv_Qty_delete", null, {
                params: { Qty_id: mainForm.value.qty_id },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    ElMessage.success('删除成功');
                    router.push('/main/Inv/InvQty');
                } else {
                    ElMessage.error('删除失败');
                }
            }).catch((err) => {
                console.log(err);
            });
        })
    }
}

function handleEdit(status) {
    if (status == "1") {
        ElMessage.info(`订单${qty_code.value}已审核,不可以进行修改`)
    } else {
        const warehouseStore = useWarehouseStore();
        warehouseStore.qty_code = qty_code.value;
        router.push('/main/Inv/InvQtyUpdate');
    }
}

// 获取单位字典
function getClassify() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "db_measure"
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        dict_labelSwer.value = result.data;
    }).catch((err) => {
        console.error(err);
    });
}

// 获取盘点类型字典
function getQtyTypeOptions() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "inv_qty"
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        qtyTypeOptions.value = result.data;
    }).catch((err) => {
        console.error(err);
    });
}

// 查询主表信息
function handle() {
    axios.get("http://localhost:5181/api/Inv_Qty/Inv_Qty_SelectCode", {
        params: {
            qty_code: qty_code.value
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {
        if (res.data && res.data.length > 0) {
            const firstItem = res.data[0];
            mainForm.value = {
                ...firstItem,
                qty_id: firstItem.qty_id,
                qty_startdate: firstItem.qty_startdate,
                qty_end: firstItem.qty_end,
                create_time: firstItem.create_time,
                qty_audit_time: firstItem.qty_audit_time,
           
            };
           
            // 设置盘点类型文本
            const typeItem = qtyTypeOptions.value.find(d => d.dict_value == firstItem.qty_type);
            qty_type_label.value = typeItem ? typeItem.dict_label : '';

        
        }
    }).catch((error) => {
        console.error("请求失败:", error);
    });
}

// 查询明细
function select() {

    axios.get("http://localhost:5181/api/Inv_Qty/Inv_Qty_SelectDetail", {
        params: {
            qty_code: qty_code.value
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then(async(res) => {
        // 创建临时数组存储产品数据
        // 创建临时数组存储产品数据
        const tempDataSwer = [];



        for (const item of res.data) {
            const stockNumber = await Select_Stock_numder(
                mainForm.value.warehouse_code,
                item.pro_code,
                item.stock_entry_no
            );

            tempDataSwer.push({
                ...item,
                stock_numder: stockNumber,   // 库存数量
            });

        }
        tableData.value = tempDataSwer;
    }).catch((err) => {
        console.error(err);
    });
}

//详情页面查询库存
function Select_Stock_numder(Waarehouse_code, Pro_code, stock_entry_no) {

    return axios.get("http://localhost:5181/api/Inv_Stock/Getinv_stock_XQ", {
        params: {
            weahouse_code: Waarehouse_code,
            por_code: Pro_code,
            stock_entry_no: stock_entry_no
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {

        return res.data;

    }).catch((res) => {
        console.log(res);
    })
}

// 日期格式化
const formatDate = (dateString) => {
    if (!dateString) return '';
    try {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (error) {
        console.error('日期格式化错误:', error);
        return dateString;
    }
};

onMounted(() => {
    select();
    getClassify();
    getQtyTypeOptions();
    handle();
    
});
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
    position: relative;
}

.section {
    margin-bottom: 20px;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
}

.label {
    display: inline-block;
    width: 80px;
    text-align: right;
    margin-right: 10px;
}

.summary-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    line-height: 40px;
    padding: 0 10px;
    background-color: #ffffff;
    border-top: none;
    width: 89.2%;
}

.summary-values {
    display: flex;
    gap: 20px;
    font-weight: bold;
}

.summary-values span {
    padding: 2px 10px;
    border-radius: 4px;
}

.button-group {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
}

.el-table {
    margin-top: 10px;
    margin-bottom: 15px;
}

.el-row {
    margin-bottom: 10px;
}
</style>